import 'package:flutter/material.dart';
import '../models/image_file.dart';

class MediaGrid extends StatelessWidget {
  final List<MediaFile> mediaFiles;
  final Function(MediaFile, int) onMediaTap;
  final MediaFile? selectedMediaFile;

  const MediaGrid({
    super.key,
    required this.mediaFiles,
    required this.onMediaTap,
    this.selectedMediaFile,
  });

  Widget _buildThumbnail(MediaFile mediaFile) {
    if (mediaFile.type == MediaType.image) {
      return Image.file(
        mediaFile.file,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          // 打印错误信息以便调试
          print('图片加载失败: ${mediaFile.path}');
          print('错误详情: $error');
          return Container(
            color: Colors.grey[300],
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.broken_image, color: Colors.grey),
                const SizedBox(height: 4),
                const Text('加载失败', style: TextStyle(fontSize: 10)),
                if (error.toString().isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: Text(
                      error.toString(),
                      style: const TextStyle(fontSize: 8, color: Colors.red),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
              ],
            ),
          );
        },
      );
    } else if (mediaFile.type == MediaType.video) {
      return Container(
        color: Colors.black87,
        child: const Stack(
          children: [
            Center(
              child: Icon(
                Icons.play_circle_outline,
                size: 48,
                color: Colors.white,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Icon(
                Icons.videocam,
                size: 24,
                color: Colors.white,
              ),
            ),
          ],
        ),
      );
    } else {
      return Container(
        color: Colors.grey[300],
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.file_present, color: Colors.grey),
            SizedBox(height: 4),
            Text('未知格式', style: TextStyle(fontSize: 10)),
          ],
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // 响应式列数
    final screenWidth = MediaQuery.of(context).size.width;
    final crossAxisCount = _calculateCrossAxisCount(screenWidth);
    
    return GridView.builder(
      padding: const EdgeInsets.all(16.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        crossAxisSpacing: 12.0,
        mainAxisSpacing: 12.0,
        childAspectRatio: 0.85, // 稍微高一点，为元数据留空间
      ),
      itemCount: mediaFiles.length,
      itemBuilder: (context, index) {
        final mediaFile = mediaFiles[index];
        return _buildMediaCard(context, mediaFile, index);
      },
    );
  }

  int _calculateCrossAxisCount(double screenWidth) {
    if (screenWidth > 1200) return 6;
    if (screenWidth > 900) return 4;
    if (screenWidth > 600) return 3;
    return 2;
  }

  Widget _buildMediaCard(BuildContext context, MediaFile mediaFile, int index) {
    final isSelected = selectedMediaFile?.path == mediaFile.path;
    
    return GestureDetector(
      onTap: () => onMediaTap(mediaFile, index),
      child: Container(
        decoration: BoxDecoration(
          color: Theme.of(context).cardColor,
          borderRadius: BorderRadius.circular(12.0),
          border: isSelected
              ? Border.all(color: Colors.blue, width: 2)
              : null,
          boxShadow: [
            BoxShadow(
              color: isSelected 
                  ? Colors.blue.withValues(alpha: 0.3)
                  : Colors.black.withValues(alpha: 0.08),
              blurRadius: isSelected ? 12.0 : 8.0,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 缩略图区域
            Expanded(
              flex: 3,
              child: ClipRRect(
                borderRadius: const BorderRadius.vertical(top: Radius.circular(12.0)),
                child: Stack(
                  children: [
                    SizedBox.expand(
                      child: _buildThumbnail(mediaFile),
                    ),
                    _buildMediaTypeOverlay(mediaFile),
                  ],
                ),
              ),
            ),
            
            // 信息区域
            Expanded(
              flex: 1,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 文件名
                    Text(
                      mediaFile.name,
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        fontWeight: FontWeight.w500,
                      ),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                    const SizedBox(height: 2),
                    
                    // 元数据信息
                    Flexible(
                      child: _buildMetadataInfo(context, mediaFile),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMediaTypeOverlay(MediaFile mediaFile) {
    if (mediaFile.type == MediaType.video) {
      return Positioned(
        top: 8,
        right: 8,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          decoration: BoxDecoration(
            color: Colors.black.withValues(alpha: 0.7),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.play_arrow, color: Colors.white, size: 12),
              if (mediaFile.durationSeconds != null) ...[
                const SizedBox(width: 2),
                Text(
                  _formatDuration(mediaFile.durationSeconds!),
                  style: const TextStyle(color: Colors.white, fontSize: 10),
                ),
              ],
            ],
          ),
        ),
      );
    }
    return const SizedBox.shrink();
  }

  Widget _buildMetadataInfo(BuildContext context, MediaFile mediaFile) {
    if (mediaFile.type == MediaType.image) {
      return _buildPhotoMetadata(context, mediaFile);
    } else if (mediaFile.type == MediaType.video) {
      return _buildVideoMetadata(context, mediaFile);
    }
    return const SizedBox.shrink();
  }

  Widget _buildPhotoMetadata(BuildContext context, MediaFile mediaFile) {
    final metadataItems = <String>[];
    
    if (mediaFile.focalLength != null) {
      metadataItems.add('${mediaFile.focalLength!.toInt()}mm');
    }
    if (mediaFile.aperture != null) {
      metadataItems.add('f/${mediaFile.aperture!.toStringAsFixed(1)}');
    }
    if (mediaFile.iso != null) {
      metadataItems.add('ISO${mediaFile.iso}');
    }
    if (mediaFile.width != null && mediaFile.height != null) {
      metadataItems.add('${mediaFile.width}×${mediaFile.height}');
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (metadataItems.isNotEmpty)
          Text(
            metadataItems.join(' • '),
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Colors.grey[600],
              fontSize: 9,
            ),
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        if (mediaFile.cameraMake != null || mediaFile.cameraModel != null) ...[
          const SizedBox(height: 2),
          Text(
            '${mediaFile.cameraMake ?? ''} ${mediaFile.cameraModel ?? ''}',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Colors.grey[500],
              fontSize: 8,
            ),
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        ],
      ],
    );
  }

  Widget _buildVideoMetadata(BuildContext context, MediaFile mediaFile) {
    final metadataItems = <String>[];
    
    if (mediaFile.durationSeconds != null) {
      metadataItems.add(_formatDuration(mediaFile.durationSeconds!));
    }
    if (mediaFile.width != null && mediaFile.height != null) {
      metadataItems.add('${mediaFile.width}×${mediaFile.height}');
    }
    if (mediaFile.codec != null) {
      metadataItems.add(mediaFile.codec!.toUpperCase());
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (metadataItems.isNotEmpty)
          Text(
            metadataItems.join(' • '),
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Colors.grey[600],
              fontSize: 9,
            ),
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        const SizedBox(height: 2),
        Text(
          '${_formatFileSize(mediaFile.size)} • ${mediaFile.extension.substring(1).toUpperCase()}',
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Colors.grey[500],
            fontSize: 8,
          ),
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
      ],
    );
  }

  String _formatDuration(double seconds) {
    final minutes = (seconds / 60).floor();
    final secs = (seconds % 60).floor();
    if (minutes > 60) {
      final hours = (minutes / 60).floor();
      final remainingMinutes = minutes % 60;
      return '$hours:${remainingMinutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    }
    return '$minutes:${secs.toString().padLeft(2, '0')}';
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '${bytes}B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
    if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
  }
}